/**
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef LIBABCKIT_SRC_IR_BUILDER_DYNAMIC_IR_BUILDER_H
#define LIBABCKIT_SRC_IR_BUILDER_DYNAMIC_IR_BUILDER_H

#include "static_core/compiler/optimizer/ir/graph.h"
#include "static_core/compiler/optimizer/ir/basicblock.h"
#include "static_core/compiler/optimizer/pass.h"
#include "libabckit/src/irbuilder_dynamic/pbc_iterator_dyn.h"
#include "libabckit/src/irbuilder_dynamic/inst_builder_dyn.h"

namespace libabckit {

/**
 * Build IR from JS bytecode
 */
class IrBuilderDynamic : public compiler::Optimization {
    struct Boundaries {
        uint32_t beginPc;
        uint32_t endPc;
    };

    struct CatchCodeBlock {
        uint32_t pc {};
        uint32_t typeId {};
    };

    // NOLINTBEGIN(misc-non-private-member-variables-in-classes)
    struct TryCodeBlock {
        Boundaries boundaries {};                        // NOLINT(misc-non-private-member-variables-in-classes)
        compiler::BasicBlock *beginBb {nullptr};         // NOLINT(misc-non-private-member-variables-in-classes)
        compiler::BasicBlock *endBb {nullptr};           // NOLINT(misc-non-private-member-variables-in-classes)
        ArenaVector<CatchCodeBlock> *catches {nullptr};  // NOLINT(misc-non-private-member-variables-in-classes)
        ArenaVector<compiler::BasicBlock *> *basicBlocks {
            nullptr};                        // NOLINT(misc-non-private-member-variables-in-classes)
        uint32_t id {compiler::INVALID_ID};  // NOLINT(misc-non-private-member-variables-in-classes)
        bool containsThrowableInst {false};  // NOLINT(misc-non-private-member-variables-in-classes)

        void Init(compiler::Graph *graph, uint32_t tryId)
        {
            id = tryId;
            auto allocator = graph->GetLocalAllocator();
            catches = allocator->New<ArenaVector<CatchCodeBlock>>(allocator->Adapter());
            beginBb = graph->CreateEmptyBlock(boundaries.beginPc);
            beginBb->SetTryBegin(true);
            endBb = graph->CreateEmptyBlock(boundaries.endPc);
            endBb->SetTryEnd(true);
            // Order of try-blocks should be saved in the graph to restore it in the generated bytecode
            graph->AppendTryBeginBlock(beginBb);
        }
    };
    // NOLINTEND(misc-non-private-member-variables-in-classes)

public:
    explicit IrBuilderDynamic(compiler::Graph *graph) : IrBuilderDynamic(graph, graph->GetMethod()) {}

    IrBuilderDynamic(compiler::Graph *graph, AbckitRuntimeAdapterDynamic::MethodPtr method)
        : Optimization(graph),
          blocks_(graph->GetLocalAllocator()->Adapter()),
          catchesPc_(graph->GetLocalAllocator()->Adapter()),
          tryBlocks_(graph->GetLocalAllocator()->Adapter()),
          openedTryBlocks_(graph->GetLocalAllocator()->Adapter()),
          catchHandlers_(graph->GetLocalAllocator()->Adapter()),
          instDefs_(graph->GetLocalAllocator()->Adapter()),
          method_(method)
    {
    }

    NO_COPY_SEMANTIC(IrBuilderDynamic);
    NO_MOVE_SEMANTIC(IrBuilderDynamic);
    ~IrBuilderDynamic() override = default;

    bool RunImpl() override;

    const char *GetPassName() const override
    {
        return "IrBuilderDynamic";
    }

    auto GetMethod() const
    {
        return method_;
    }

private:
    void CreateBlock(size_t pc)
    {
        if (blocks_[pc] == nullptr) {
            blocks_[pc] = GetGraph()->CreateEmptyBlock();
            blocks_[pc]->SetGuestPc(pc);
        }
    }

    compiler::BasicBlock *GetBlockForPc(size_t pc)
    {
        return blocks_[pc];
    }

    compiler::BasicBlock *GetPrevBlockForPc(size_t pc)
    {
        do {
            ASSERT(pc > 0);
            pc--;
        } while (blocks_[pc] == nullptr || blocks_[pc]->GetGraph() == nullptr);
        return blocks_[pc];
    }

    bool CheckMethodLimitations(const BytecodeInstructions &instructions, size_t vregsCount);
    void BuildBasicBlocks(const BytecodeInstructions &instructions);
    bool BuildBasicBlock(compiler::BasicBlock *bb, InstBuilder *instBuilder, const uint8_t *instructionsBuf);
    bool BuildInstructionsForBB(compiler::BasicBlock *bb, InstBuilder *instBuilder, const uint8_t *instructionsBuf);
    void SplitConstant(compiler::ConstantInst *constInst);

    struct BlocksConnectorInfo {
        bool fallthrough {};
        bool deadInstructions {};
        BytecodeInst prevInst {nullptr};
    };

    compiler::BasicBlock *AddSuccs(BlocksConnectorInfo *info, compiler::BasicBlock *currBb,
                                   compiler::BasicBlock *targetBlock, size_t &pc, BytecodeInst &inst);
    void ConnectBasicBlocks(const BytecodeInstructions &instructions);
    void CreateTryCatchBoundariesBlocks();
    void ResolveTryCatchBlocks();
    void ConnectTryCatchBlocks();
    IrBuilderDynamic::TryCodeBlock *InsertTryBlockInfo(const Boundaries &tryBoundaries);
    void TrackTryBoundaries(size_t pc);
    compiler::BasicBlock *GetBlockToJump(BytecodeInst *inst, size_t pc);
    compiler::BasicBlock *GetBlockForSaveStateDeoptimize(compiler::BasicBlock *block);
    void MarkTryCatchBlocks(compiler::Marker marker);
    template <class Callback>
    void EnumerateTryBlocksCoveredPc(uint32_t pc, const Callback &callback);
    void ConnectTryCodeBlock(const TryCodeBlock &tryBlock,
                             const ArenaMap<uint32_t, compiler::BasicBlock *> &catchBlocks);
    void ProcessThrowableInstructions(InstBuilder *instBuilder, compiler::Inst *throwableInst);
    void RestoreTryEnd(const TryCodeBlock &tryBlock);

private:
    ArenaVector<compiler::BasicBlock *> blocks_;
    ArenaSet<uint32_t> catchesPc_;
    ArenaMultiMap<uint32_t, TryCodeBlock> tryBlocks_;
    ArenaList<TryCodeBlock *> openedTryBlocks_;
    ArenaUnorderedSet<compiler::BasicBlock *> catchHandlers_;
    compiler::InstVector instDefs_;
    AbckitRuntimeAdapterDynamic::MethodPtr method_ = nullptr;
};

}  // namespace libabckit

#endif  // LIBABCKIT_SRC_IR_BUILDER_DYNAMIC_IR_BUILDER_H
